// page/component/new-pages/user/user.js
const db = wx.cloud.database()
const app = getApp()
Page({
  data:{
    thumb:'cloud://booking-8goe6l0we781655c.626f-booking-8goe6l0we781655c-1306210661/showserve/mmexport1624331363852.jpg',
    nickname:'fzz',
    orders:[],
    hasAddress:false,
    address:{},
    
  },
  onLoad(){
    
    /**
     * 获取用户信息
     */
    wx.getUserInfo({
      success:(res)=>{
        this.setData({
          thumb: res.userInfo.avatarUrl,
          nickname: res.userInfo.nickName
        })
      }
    }),
    
    /**
     * 发起请求获取订单列表信息
     */
    wx.request({
      url: 'http://www.gdfengshuo.com/api/wx/orders.txt',
      success:(res)=>{
        this.setData({
          orders: res.data
        })
      }
      
    })
    this.getUserAddress()
    this.getOrder()
  },

  // 从云数据库获取用户地址信息

  getUserAddress(){
    db.collection("sg_address").where({_openid:app.globalData.openid}).get({
      success:(res)=>{
        console.log(res.data[0])
        this.setData({
          address:res.data[0],
          hasAddress:true
        })
          wx.setStorage({
            key: 'address',
            data: this.data.address,
            
          })
        
      }
     
    })
  },
  getOrder(){
  db.collection("sg_order").where({_openid:app.globalData._openid}).get({
    success:(res)=>{
      console.log(res)
      this.setData({
        orders:res.data[0].order
      })
      console.log(this.data.orders)
    }
  })
  },
  onShow(){
    this.getOrder()
    /**
     * 获取本地缓存 地址信息
     */
    wx.getStorage({
      key: 'address',
      success:(res)=>{
        this.setData({
          hasAddress: true,
          address: res.data
        })
      }
    })
  },
  /* 发起支付请求*/
  payOrders(){
    wx.requestPayment({
      timeStamp: 'String1',
      nonceStr: 'String2',
      package: 'String3',
      signType: 'MD5',
      paySign: 'String4',
      success: function(res){
        console.log(res)
      },
      fail: function(res) {
        wx.showModal({
          title:'支付提示',
          content:'<text>',
          showCancel: false
        })
      }
    })
  },
  /* 点击取消订单按钮，删除订单*/
  deleteOrder(e){
    let index = e.currentTarget.dataset.index
    let orders = this.data.orders;
    orders.splice(index,1);
    this.setData({
      orders:orders
    })
    console.log("执行了删除订单")
    db.collection("sg_order").doc(app.globalData._openid).update({
      data:{
        _openid: app.globalData._openid,
        order: this.data.orders
      }
    })
  }
})